package com.learn.redis.config;

import com.learn.redis.common.constants.RedisConstants;
import com.learn.redis.config.properties.SingleProperties;
import com.learn.redis.utils.idempotent.DefaultIdempotentUtil;
import com.learn.redis.utils.idempotent.Idempotent;
import org.apache.commons.lang3.BooleanUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * redisson配置类
 *
 * @author PC
 */
@Configuration
public class CusRedissonConfiguration {
    private final static String REDIS_ADDRESS_PATTERN = "%s://%s:%s";

    @Bean
    public RedissonClient singleRedissonClient(SingleProperties singleProperties) {
        Config config = new Config();
        config.useSingleServer().setAddress(String.format(REDIS_ADDRESS_PATTERN,
                        BooleanUtils.isTrue(singleProperties.getEncryptEnabled()) ?
                                RedisConstants.redisProtocol.ENCRYPT_REDIS : RedisConstants.redisProtocol.REDIS,
                        singleProperties.getHost(), singleProperties.getPort()))
                .setUsername(singleProperties.getUsername()).setPassword(singleProperties.getPassword());
        return Redisson.create(config);
    }

    @Bean
    @ConditionalOnProperty(prefix = "cus.redisson", name = "idempotent-default", havingValue = "true", matchIfMissing = true)
    public Idempotent idempotent(){
        return new DefaultIdempotentUtil();
    }

}
